GBML manual / Instances

instance_exists

True if a reference still points at a live instance.

Syntax

instance_exists(id) -> bool

Arguments

NameType
idref<object>

Returns

bool

Description

Tells you whether a reference you are holding still points at something alive. This is exact, not a guess: a reference carries its own generation number, so a stale reference to a slot that was freed and handed to a brand new instance correctly reads as gone - it never mistakes the new occupant for the old one.

A reference typed as a parent can point at any of its children, and instance_exists works for them the same way.

An instance you destroyed with instance_destroy still exists until the end of that frame, because it finishes the frame first. instance_exists says yes for it in the rest of that frame, and no from the next frame on.

The natural pairing is instance_create: keep the ref it hands back in an instance variable, and check instance_exists on it before reading anything off that reference later.

Example

var maybe_target = instance_nearest(x, y, obj_doc_target);
if (maybe_target != nothing && instance_exists(maybe_target)) {
    var target = maybe_target;
}

A defensive pattern: only commits the freshly-found instance to target after confirming it is still real. Both maybe_target and target are locals (var) here, purely to isolate this check; a real turret would instead have target already declared as a genuine instance variable in its own Create event (see Variables, types and scope), with this same if reassigning that field from Step.

On the GBA

Exact, not "probably": a reference carries a generation number, so a stale reference to a freed-and-reused slot correctly reads as gone rather than matching the new occupant. One thing it deliberately does NOT mean: an instance you destroyed earlier in THIS frame still reads as existing, because its slot is only freed at the end of the frame - see instance_destroy for why, and for the loop shape to avoid.

See also: instance_destroyinstance_nearest